package com.order.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.order.view.ItemView;
import com.order.view.OrderView;
import com.vrsys.domain.Order;
import com.vrsys.domain.OrderhasItem;
import com.vrsys.persistence.OrderDao;

@Component("orderService")
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderView orderView;

    public void save(List<ItemView> itemView) {
        Order order = saveOrder(itemView);
        saveOrderhasItem(itemView, order);
        orderView.getOrders().add(order);
    }

    public Order saveOrder(List<ItemView> itemView){
        double totalPrice = 0.0;
        for (ItemView item : itemView) {
            totalPrice += item.getItemPrice();
        }
        Order order = new Order();
        order.setTotalPrice(new BigDecimal(totalPrice));
        order.setCode("O100" + System.currentTimeMillis());
        orderDao.saveOrderAndgetId(order);

        return order;
    }

    public void saveOrderhasItem(List<ItemView> itemView, Order order){
        List<OrderhasItem> orderhasItem = new ArrayList<OrderhasItem>();
        for (ItemView view : itemView) {
            OrderhasItem orderItem = new OrderhasItem();
            orderItem.setOrderId(order.getId());
            orderItem.setItemId(view.getItemId());
            orderItem.setQuantity(view.getItemQty());
            orderhasItem.add(orderItem);
        }
        orderDao.saveOrderhasItem(orderhasItem);
    }

    public OrderDao getOrderDao() {
        return orderDao;
    }

    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public OrderView getOrderView() {
        return orderView;
    }

    public void setOrderView(OrderView orderView) {
        this.orderView = orderView;
    }
}
